<template>
  <a-form style="padding-left: 46px" class="edit-people-form" :form="form" layout="inline">
    <a-row class="mb10">
      <a-col>
        <a-form-item v-show="false" class="name-label" label="ID">
          <a-input :disabled="true" v-decorator="['linkmanId', { rules: [], initialValue: null }]" />
        </a-form-item>
        <a-form-item v-show="false" class="name-label" label="供应商">
          <!-- <a-select
            placeholder="请选择"
            style="width: 645px"
            v-decorator="['supplierCode', { rules: [], initialValue: null}]"
            allowClear
          >
            <a-select-option
              v-for="item in supplierData"
              :key="item.supplierCode"
            >{{ item.supplierName }}</a-select-option>
          </a-select>-->
        </a-form-item>
      </a-col>
    </a-row>
    <a-row class="mb10" :gutter="10">
      <a-col :span="10" :md="11" :sm="13">
        <a-form-item class="name-label" label="姓名">
          <a-input
            style="width: 120px"
            placeholder="请输入"
            v-decorator="['linkmanName', { rules: [{required: true, message: '请输入姓名'}], validateTrigger: 'change' }]"
          />
        </a-form-item>
        <a-form-item label="头衔">
          <a-input
            style="width: 120px"
            placeholder="请输入"
            v-decorator="['linkmanTitle', { rules: [{required: true, message: '请输入头衔'}], validateTrigger: 'change' }]"
          />
        </a-form-item>
      </a-col>
      <a-col :span="12" :md="11">
        <a-form-item style="display:flex" class="phone-label" label="联系电话">
          <a-input
            placeholder="请输入"
            v-decorator="['linkmanTel', { rules: [{required: true, message: '请输入联系电话', pattern: /^1[3456789]\d{9}$/}], validateTrigger: 'change' }]"
          />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row class="mb10">
      <a-col :span="10" :md="11">
        <a-form-item class="name-label" label="身份证号">
          <a-input
            style="width: 220px"
            placeholder="请输入"
            v-decorator="['idcard', { rules: [{required: true, message: '身份证号码输入错误', pattern: /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/}], validateTrigger: 'change' }]"
          />
        </a-form-item>
      </a-col>
      <a-col :span="12">
        <a-form-item class="date-label1" label="身份证号到期日期">
          <a-date-picker
            placeholer="上传识别输入"
            v-decorator="['idcardEnd', { rules: [{required: true, message: '请添加一个联系人'}], validateTrigger: 'change' }]"
          />
        </a-form-item>
        <a-form-item v-show="false" class="date-label1" label="身份证前ID">
          <a-input
            :disabled="true"
            v-decorator="['idcardFront', { rules: [], initialValue: null }]"
          />
        </a-form-item>
        <a-form-item v-show="false" class="date-label1" label="身份证后ID">
          <a-input
            :disabled="true"
            v-decorator="['idcardBack', { rules: [], initialValue: null }]"
          />
        </a-form-item>
        <a-form-item v-show="false" class="date-label1" label="购销资格证ID">
          <a-input
            :disabled="true"
            v-decorator="['qualification', { rules: [], initialValue: null }]"
          />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row class="mb10">
      <a-col :span="10" :md="11">
        <!-- <a-form-item class="pl20">
          <a-checkbox
            :checked="salesmanFlag"
            @change="saleManChange"
            v-decorator="['salesmanFlag', { rules: [], initialValue: 0 }]"
          >是否业务员</a-checkbox>
        </a-form-item>-->
      </a-col>
      <a-col :span="12">
        <a-form-item class="date-label1" label="购销资格证到期日期">
          <a-date-picker v-decorator="['qualificationEnd', { rules: [], initialValue: null }]" />
        </a-form-item>
      </a-col>
    </a-row>
    <a-row :gutter="10">
      <a-col :span="8">
        <a-form-item>
          <a-upload
            listType="picture-card"
            :fileList="idcardFront"
            class="avatar-uploader"
            :beforeUpload="beforeUpload"
            @preview="handlePreview"
            @change="info => handleChange(info, 1)"
            :customRequest="info => customRequest(info, 'front')"
            :remove="info => handleRemove(info, 'front')"
          >
            <div v-if="idcardFront.length < 1">
              <img style="width: 240px" :src="idcardZ" alt="示例" />
              <div class="ant-upload-text">身份证正面示例图片，点击上传</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item>
          <a-upload
            listType="picture-card"
            :fileList="idcardBack"
            class="avatar-uploader"
            :beforeUpload="beforeUpload"
            @preview="handlePreview"
            @change="info => handleChange(info, 2)"
            :customRequest="info => customRequest(info, 'back')"
            :remove="info => handleRemove(info, 'back')"
            v-decorator="['idcardFrontPic', { rules: [{required: true, message: '新增需添加一个联系人'}], initialValue: null }]"
          >
            <div v-if="idcardBack.length < 1">
              <img style="width: 240px" :src="idcardF" alt="示例" />
              <div class="ant-upload-text">身份证反面示例图片，点击上传</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item>
          <a-upload
            listType="picture-card"
            :fileList="qualificationList"
            class="avatar-uploader avatar-uploader-last"
            :beforeUpload="beforeUpload"
            @preview="handlePreview"
            @change="info => handleChange(info, 'qualification')"
            :customRequest="customRequest"
          >
            <div v-if="qualificationList.length < 1">
              <a-icon type="plus" />
              <!-- <img style="width: 240px" :src="demoImg" alt="示例" /> -->
              <div class="ant-upload-text">购销资格证图片，点击上传</div>
            </div>
          </a-upload>
        </a-form-item>
      </a-col>
    </a-row>
    <preview-modal ref="previewModal" />
  </a-form>
</template>

<script>
import idcardZ from '@/assets/idcard_z.jpeg'
import idcardF from '@/assets/idcard_f.jpeg'
import demoImg from '@/assets/license.jpeg'
import { saveOnlyUploads, updateLinkMan, insertLinkMan, allLinkInfo, idcardFrontUpload, idcardBackUpload, showUrlById, deleteUploadPic } from '@/api/supplier'
import { openNotification, getBase64, formatY } from '@/utils/util'
import PreviewModal from '@/components/PreviewModal'
import pick from 'lodash.pick'

export default {
  components: {
    PreviewModal
  },
  data() {
    return {
      idcardZ,
      idcardF,
      demoImg,
      imageUrl: '',
      idcardFront: [], // 身份证正面图片显示数组
      idcardBack: [], // 身份证反面图片显示数组
      qualificationList: [], // 购销资格证图片显示数组
      form: this.$form.createForm(this),
      confirmLoading: false,
      mdl: {}, // 存储编辑传递过来的record数据
      imgInfo: {},
      isSaleMan: false,
      // qualificationEnd: null,
      salesmanFlag: false
      // supplierData: [] // 供应商数组数据
    }
  },
  // mounted() {
  //   // 供应商数据获取
  //   allLinkInfo().then(res => {
  //     this.supplierData = res.data
  //   })
  // },
  methods: {
    reset() {
      this.form.resetFields()
    },
    getFormData() {
      const {
        form: { validateFields }
      } = this

      validateFields(
        ['linkmanId', 'linkmanName', 'idcardFront', 'idcardBack', 'qualification', 'linkmanTitle', 'supplierCode', 'linkmanTel', 'salesmanFlag', 'idcard', 'idcardEnd', 'qualificationEnd'],
        { force: true },
        async (err, values) => {
          if (!err) {
            const { salesmanFlag, qualification, idcardFront, idcardBack, idcardEnd, qualificationEnd } = values
            const param = { ...values, idcardEnd: formatY(idcardEnd), qualificationEnd: formatY(qualificationEnd) }
            if (salesmanFlag) {
              if (qualification && qualificationEnd) {
                // 勾选业务员，且证件和日期已填
                console.log('people values', { ...param })
                this.$emit('sendData', param, 3)
              } else {
                this.$message.error('业务员必须上传购销资格证')
              }
            } else {
              console.log('people values', { ...param })
              this.$emit('sendData', { ...param }, 3)
            }
          } else {
            this.$emit('notSubmit', false, 3)
          }
        }
      )
    },
    edit(type, record) {
      console.log('edit', type, record)
      this.form.resetFields()
      if (type !== 'add') {
        // if (record.qualificationEnd !== null) {
        //   this.qualificationEnd = record.qualificationEnd
        // }
        this.isSaleMan = record.salesmanFlag
        this.salesmanFlag = record.salesmanFlag
        // 不是新增的其他情况都通过 linkmanId 去查已上传的图片回显过来
        showUrlById(record.linkmanId).then(res => {
          console.log('res', res)
          if (res.data) {
            if (res.data.idcardFront) {
              this.idcardFront = [{ uid: '0', name: 'idcardFront', url: res.data.idcardFrontSavePath }]
            }
            if (res.data.idcardBack) {
              this.idcardBack = [{ uid: '1', name: 'idcardBack', url: res.data.idcardBackSavePath }]
            }
            if (res.data.qualification) {
              this.qualificationList = [{ uid: '2', name: 'qualification', url: res.data.qualificationkSavePath }]
            }
          }
        })
      }
      if (type !== 'add') {
        this.mdl = Object.assign({}, record)
        this.$nextTick(() => {
          this.form.setFieldsValue({
            qualificationEnd: this.moment(record.qualificationEnd),
            idcardEnd: this.moment(record.idcardEnd)
          })
        })
      } else {
        this.mdl = Object.assign({}, record)
      }
      console.log('editPeople mdl', this.mdl)
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.mdl, 'idcardFront', 'idcardBack', 'qualification', 'linkmanId', 'linkmanName', 'supplierCode', 'linkmanTitle', 'linkmanTel', 'salesmanFlag', 'idcard'))
      })
    },
    // 勾选是否业务员
    saleManChange(e) {
      this.isSaleMan = e.target.checked
      this.salesmanFlag = e.target.checked
    },
    // 预览图片，显示大图
    handlePreview(file) {
      console.log('file', file)
      this.$refs.previewModal.show([file.url])
    },
    handleChange(info, arr) {
      console.log('info', info, arr)
      this.imgInfo = info
      switch (arr) {
        case 1:
          this.idcardFront = info.fileList
          break
        case 2:
          this.idcardBack = info.fileList
          break
        default:
          this.qualificationList = info.fileList
          break
      }
      arr = info.fileList
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        // Get this url from response in real world.
        getBase64(info.file.originFileObj, imageUrl => {
          this.imageUrl = imageUrl
          console.log('info', info, arr, imageUrl)

          this.loading = false
        })
      }
    },
    handleRemove(info, type) {
      console.log('remove info', info)
      let id = ''
      if (type === 'front') {
        id = this.form.getFieldValue('idcardFront')
        this.idcardFront = []
        this.$nextTick(() => {
          this.form.setFieldsValue({
            idcard: ''
          })
        })
      } else if (type === 'back') {
        id = this.form.getFieldValue('idcardBack')
        this.idcardBack = []
        this.$nextTick(() => {
          this.form.setFieldsValue({
            idcardEnd: ''
          })
        })
      } else {
        id = this.form.getFieldValue('qualification')
        this.qualificationList = []
        this.$nextTick(() => {
          this.form.setFieldsValue({
            qualification: '',
            qualificationEnd: ''
          })
        })
      }
    },
    // 覆盖原本的上传方法
    customRequest(info, local) {
      console.log('customRequest', info)
      const formData = new FormData()
      formData.append('file', info.file)
      // 调方法，post，body 放入 formData
      if (local === 'front') {
        idcardFrontUpload(formData).then(res => {
          if (res.data !== null) {
            const { data } = res
            if (data[1].idCardNum && data[1].name) {
              console.log('imgInfo', this.imgInfo)
              this.$nextTick(() => {
                this.form.setFieldsValue({
                  linkmanName: data[1].name,
                  idcard: data[1].idCardNum,
                  idcardFront: data[0].uploadId
                })
              })
            } else {
              this.$message.error('您上传的可能不是身份证照片或照片识别有误，请上传正确的身份证照片')
            }
            this.idcardFront = [{ ...this.imgInfo.fileList[0], status: 'done', url: data[0].savePath }]
          }
        })
      } else if (local === 'back') {
        idcardBackUpload(formData).then(res => {
          if (res.data !== null) {
            const { data } = res
            console.log('data', data)
            if (data[1].expiryDate) {
              const expiryDate = data[1].expiryDate
              const year = expiryDate.substr(0, 4)
              const mon = expiryDate.substr(4, 2)
              const day = expiryDate.substr(6, 2)
              const date = year + '-' + mon + '-' + day
              console.log('date', year, mon, day)
              this.$nextTick(() => {
                this.form.setFieldsValue({
                  idcardEnd: this.moment(date),
                  idcardBack: data[0].uploadId
                })
              })
            } else {
              this.$message.error('您上传的可能不是身份证照片或照片识别有误，请上传正确的身份证照片')
            }
            this.idcardBack = [{ ...this.imgInfo.fileList[0], status: 'done', url: data[0].savePath }]
          }
        })
      } else {
        saveOnlyUploads(formData).then(res => {
          if (res.data !== null) {
            this.$message.info('购销资格证暂不能识别到期日期，请手动选择')
            const { data } = res
            this.qualificationList = [{ ...this.imgInfo.fileList[0], status: 'done', url: data.fileUrl + data.fileName }]
            this.$nextTick(() => {
              this.form.setFieldsValue({
                qualification: data.uploadId
              })
            })
          }
        })
      }
    }
  }
}
</script>

<style scoped>
.w330 {
  width: 230px;
}
.avatar-uploader >>> .ant-upload-list-item {
  width: 258px;
  height: 189px;
}
.avatar-uploader-last >>> .ant-upload {
  width: 200px;
  height: 200px;
}
.edit-people-form >>> .name-label .ant-form-item-label {
  width: 77px;
}
.edit-people-form >>> .phone-label .ant-form-item-label {
  width: 151px;
}
.edit-people-form >>> .date-label1 .ant-form-item-label {
  width: 156px;
}
</style>
